package avicit.bdp.dgs.qa.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.dgs.qa.dao.AlarmConfigDAO;
import avicit.bdp.dgs.qa.dto.AlarmConfigDTO;
import avicit.bdp.dgs.qa.utils.enums.*;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-03-30
 * @类说明：AlarmService
 * @修改记录：
 * @注意事项：
 * @主要功能：质量规则校验Service
 */
@Service
public class AlarmService extends BaseService<AlarmConfigDAO, AlarmConfigDTO> {
    private static final Logger logger = LoggerFactory.getLogger(AlarmService.class);

    @Autowired
    private ConvertColumnClient convertColumnClient;

    /**
     * 根据规则ID获取告警配置列表
     * @param ruleId
     * @return
     */
    @Transactional
    public List<AlarmConfigDTO> getAlarmList(String ruleId) {
        List<AlarmConfigDTO> alarmList = this.mapper.getAlarmListByCond(ruleId);

        valueConvert(alarmList);

        return alarmList;
    }

    /**
     * 批量插入
     * @param ruleId
     * @param templateId
     * @param alarmList
     */
    @Transactional
    public void batchInsertRuleAlarm(String ruleId, String templateId, List<AlarmConfigDTO>alarmList) {
        if (CollectionUtils.isEmpty(alarmList)) {
            throw new BusinessException("未配置告警.");
        }
        if (StringUtils.isBlank(ruleId)) {
            throw new BusinessException("规则ID为空，插入失败");
        }

        List<AlarmConfigDTO> finalAlarmList = Lists.newArrayList();
        for (AlarmConfigDTO dto : alarmList) {
            if (dto == null) {
                continue;
            }
            if (!checkAddValid(dto)) {
                continue;
            }

            dto.setId(ComUtil.getId());
            dto.setRuleId(ruleId);
            dto.setTemplateId(templateId);
            PojoUtil.setSysProperties(dto, PlatformConstant.OpType.insert);

            finalAlarmList.add(dto);
        }

        if (CollectionUtils.isNotEmpty(finalAlarmList)) {
            this.mapper.batchInsertRuleAlarm(finalAlarmList);
        }
    }

    /**
     * 批量更新
     * @param ruleId
     * @param templateId
     * @param dsList
     */
    @Transactional
    public void batchUpdateRuleAlarm(String ruleId, String templateId, List<AlarmConfigDTO> dsList) {
        this.mapper.deleteAlarmByCond(ruleId, null);

        batchInsertRuleAlarm(ruleId, templateId, dsList);
    }

    /**
     * 删除/批量删除规则告警
     * @param ruleId 规则ID
     * @param idList 告警ID列表
     * @return
     */
    @Transactional
    public int deleteAlarmByCond(String ruleId, List<String> idList) {
        return this.mapper.deleteAlarmByCond(ruleId, idList);
    }

    /**
     * 合法性检查
     * @param dto
     * @return
     */
    private boolean checkAddValid(AlarmConfigDTO dto) {
        if (dto == null) {
            return false;
        }

        if (dto.getCheckType() != null) {
            if (CheckType.getDescByCode(dto.getCheckType()) == null) {
                logger.warn("校验类型不合法,当前值：" + dto.getCheckType() + ",取值范围[0,1]");
                return false;
            }
        }

        if (dto.getCheckMode() != null) {
            if (CheckMode.getDescByCode(dto.getCheckMode()) == null) {
                logger.warn("校验方式不合法,当前值：" + dto.getCheckType() + ",取值范围[0,9]");
                return false;
            }
        }

        return true;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     * @param dtoList
     */
    private void valueConvert(List<AlarmConfigDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }

        // 设置创建者名称
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (AlarmConfigDTO dto : dtoList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, dto.getCreatedBy());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (AlarmConfigDTO dto : dtoList) {
                dto.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, dto.getCreatedBy()));
            }
        }

        // 设置枚举类型
        for (AlarmConfigDTO dto : dtoList) {
            dto.setCheckTypeName(CheckType.getDescByCode(dto.getCheckType()));
            dto.setCheckModeName(CheckMode.getDescByCode(dto.getCheckMode()));
            dto.setLowerCcompareTypeName(CompareType.getDescByCode(dto.getLowerCompareType()));
            dto.setUpperCcompareTypeName(CompareType.getDescByCode(dto.getUpperCompareType()));
        }
    }
}
